package com.kqb.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kqb.common.curd.impl.BaseServiceImpl;
import com.kqb.common.domain.page.PageResult;
import com.kqb.common.exception.BusinessException;
import com.kqb.common.utils.Assert;
import com.kqb.mapper.ForwarderMapper;
import com.kqb.mapper.ForwarderUserMapper;
import com.kqb.pojo.dto.ForwarderDto;
import com.kqb.pojo.User;
import com.kqb.pojo.UserType;
import com.kqb.query.ForwarderQuery;
import com.kqb.service.ForwarderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service
public class ForwarderServiceImpl extends BaseServiceImpl<ForwarderDto, ForwarderMapper> implements ForwarderService {


    @Autowired
    ForwarderUserMapper forwarderUserMapper;


    @Override
    public PageResult query(ForwarderQuery query) {
        //分页查询
        PageHelper.startPage(query.getPageNum(), query.getPageSize());//后面紧跟查询
        List list = iBaseMapper.query(query);
        PageInfo info = new PageInfo(list);
        return new PageResult(query.getPageNum(), query.getPageSize(), info.getTotal(), list);
    }

    @Override
    public PageResult queryByMap(Map map) {
        int page=1;     //当前第几页
        int pageSize=10;       //默认每页记录数
        if(map.containsKey("pageNum")){
            page = Integer.parseInt(map.get("pageNum").toString());
        }

        if(map.containsKey("pageSize")){
            pageSize=Integer.parseInt(map.get("pageSize").toString());
        }
        PageHelper.startPage(page,pageSize);
        List list=iBaseMapper.queryByMap(map);
        PageInfo info=new PageInfo(list);
        return new PageResult(page,pageSize,info.getTotal(),list);
    }

    /**
     * 保存货代信息
     * @param entity
     * @return
     */
    @Override
    public int save(ForwarderDto entity) {
        //检验账户是否存在
        int count = forwarderUserMapper.queryByName(entity.getAccount());
        if (count > 0)
            throw new BusinessException("该账号已存在！");
        User user = new User(entity.getAccount(), entity.getPassword(), UserType.FORWARDER_USER);
        int re = forwarderUserMapper.save(user);
        Assert.isZero(re,"保存用户失败!");
        entity.setId(user.getId());
        return super.save(entity);
    }

    /**
     * 删除货代
     * @param id
     * @return
     */
    @Transactional
    @Override
    public int delete(Serializable id) {
        int re = forwarderUserMapper.delete(id);
        Assert.isZero(re,"删除用户失败!");
        return super.delete(id);
    }
}
